package cn.edu.buaa.cnsatm.traffic_big_data_server.highway.service;

import cn.edu.buaa.cnsatm.traffic_big_data_server.highway.dao.HighwayCongestionDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.JDBCUtil;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.JsonArrayToGeoJsonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.artemis.api.core.Pair;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;

public class HighwayThread implements Runnable{
    public String highwayName;
    public static JSONArray jsonArray;


    public HighwayThread(String highwayName) {
        this.highwayName = highwayName;
        System.out.println(this.highwayName + " 创建成功");
    }
    @Override
    public void run(){
        System.out.println(this.highwayName + " 开始工作");
        try {
            ResultSet resultSet = HighwayCongestionDAO.getHighwayLocationByHighwayName(this.highwayName);
            System.out.println(this.highwayName + " 获取数据成功，正在将数据转为json");
            addToJson(resultSet);
            //System.out.println(this.getName() + "完成" + String.valueOf(AirRouteService.getAirRouteCapacityOffLine(dateStringList.get(dateIndex))));
            resultSet.getStatement().close();
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(this.highwayName + " 工作结束");
    }
    public static synchronized void addToJson(ResultSet resultSet) throws SQLException {
        while(resultSet.next()){
            JSONObject jo = JSON.parseObject(JsonArrayToGeoJsonUtil.wkbToJson(resultSet.getString("geom")));
            //System.out.println(jo.toJSONString());
            jsonArray.add(jo);
            //System.out.println(jsonArray.toJSONString());
        }
    }
    public static void main(String args[]) throws SQLException {
        JDBCUtil.startConnection();
        ResultSet mainHighWaySet = HighwayCongestionDAO.getAllMainHighWay();
        HashSet<Pair<String, String>> mainHighwayMap = new HashSet<>();
        while(mainHighWaySet.next()){
            mainHighwayMap.add(
                    new Pair<>(mainHighWaySet.getString("highway_name"),
                            mainHighWaySet.getString("highway_code")
                    ));
        }
        HighwayThread highwayThread[] = new HighwayThread[mainHighwayMap.size()];
        int iter = 0;
        HighwayThread.jsonArray = new JSONArray();
        for(Pair<String, String> highway: mainHighwayMap){
            highwayThread[iter] = new HighwayThread(highway.getA());
            Thread thread = new Thread(highwayThread[iter]);
            thread.start();
        }
        System.out.println(jsonArray);
    }
}
